
/*封装axios库 方式  基础版*/

import axios from 'axios'
import Cookies from "js-cookie";
import router from "../router";
import domain from "../../domain";
import {Message} from "element-ui"

const target = domain.target
//create an axios instance
const service = axios.create({
  baseURL: target, // api 的 base_url
  timeout: 5000 // request timeout //设置请求时长
})

service.interceptors.request.use(config => {
  // 在发送请求之前做些什么
  // 判断是否存在token，如果存在将每个页面header都添加token

  var token = Cookies.get('token')
  if (token != null && token !== '') {
    config.headers.common['Authorization'] = ' Bearer ' + token
  }
  return config
}, error => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

service.interceptors.response.use(function(response) {
  return response
}, function(error) {
  if (error.response) {
    switch (error.response.status) {
      case 401:
        router.replace({
          path: '/login',
          query: { redirect: router.currentRoute.fullPath }
        })
        Cookies.remove('user')
        Cookies.remove('token')
        Cookies.remove('refresh_token')
        Cookies.remove('realusername')
    }
  }
  return Promise.reject(error)
})


// get请求
export const $get = function (url, config) {
  if (!url) throw Error('请核对请求链接是否正确')
  // const token = window.localStorage.storetoken
  const {params, headers, ...otherConfig} = config
  const header = Object.assign(headers || {}, {
    'Content-Type': 'application/json; charset=utf-8',
    // 'Auth-Token': token,
    // 'Common-Param': getCommonParam()
  })
  return service.get(url, {
    params,
    headers: header,
    ...otherConfig,
  }).catch((error)=>{Message.error(error)})
}
// post请求
export const $post = function (url, params, config = {}, type=1) {
  if (!url) throw Error('请核对请求链接是否正确')
  // const token = window.localStorage.storetoken
  // const {...otherConfig} = config
  let source
  if (type==1){
    source = {'Content-Type': 'application/json; charset=utf-8'} // json 数据
  }else if (type==2){
    source = {'Content-Type': 'multipart/form-data'} // formData表单
  }else{
    source = {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'} // 普通表单
  }
  const header = Object.assign(  {}, source)
  return service.post(url, params, {
    headers: header,
    ...config,
  }).catch((error)=>{Message.error(error)})
}


// main.js 导入
// Vue.$get = Vue.prototype.$get = $get
// Vue.$post = Vue.prototype.$post = $post


